home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C16 / Mblock.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.1 KB  |  55 lines

  1. //: C16:Mblock.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Built-in types in templates
  7. #include "../require.h"
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. template<class T, int size = 100>
  12. class Mblock {
  13.   T array[size];
  14. public:
  15.   T& operator[](int index) {
  16.     require(index >= 0 && index < size);
  17.     return array[index];
  18.   }
  19. };
  20.  
  21. class Number {
  22.   float f;
  23. public:
  24.   Number(float ff = 0.0f) : f(ff) {}
  25.   Number& operator=(const Number& n) {
  26.     f = n.f;
  27.     return *this;
  28.   }
  29.   operator float() const { return f; }
  30.   friend ostream&
  31.     operator<<(ostream& os, const Number& x) {
  32.       return os << x.f;
  33.   }
  34. };
  35.  
  36. template<class T, int sz = 20>
  37. class Holder {
  38.   Mblock<T, sz>* np;
  39. public:
  40.   Holder() : np(0) {}
  41.   T& operator[](int i) {
  42.     require(i >= 0 && i < sz);
  43.     if(!np) np = new Mblock<T, sz>;
  44.     return np->operator[](i);
  45.   }
  46. };
  47.  
  48. int main() {
  49.   Holder<Number, 20> h;
  50.   for(int i = 0; i < 20; i++)
  51.     h[i] = i;
  52.   for(int j = 0; j < 20; j++)
  53.     cout << h[j] << endl;
  54. } ///:~
  55.